<?php

namespace App\Providers\Hall;

use InvalidArgumentException;
use Illuminate\Redis\RedisManager;
use App\Services\HallDomainService;

/**
 * @mixin \Illuminate\Redis\Connections\Connection
 */
class HallRedisManager extends RedisManager
{

    /**
     * Get a Redis connection by name.
     *
     * @param  string|null  $name
     * @return \Illuminate\Redis\Connections\Connection
     */
    public function connection($name = null)
    {
        // 以hall_id为库
        if (!$name) {
            $hallID = HallDomainService::getHallID();
            $name = "hall-$hallID";
        }

        if (isset($this->connections[$name])) {
            return $this->connections[$name];
        }

        return $this->connections[$name] = $this->resolve($name);
    }

    /**
     * Resolve the given connection by name.
     *
     * @param  string|null  $name
     * @return \Illuminate\Redis\Connections\Connection
     *
     * @throws \InvalidArgumentException
     */
    public function resolve($name = null)
    {
        // 以hall_id为库
        if (!$name) {
            $hallID = HallDomainService::getHallID();
            $name = "hall-$hallID";
        }

        $options = $this->config['options'] ?? [];

        if (isset($this->config[$name])) {
            return $this->connector()->connect($this->config[$name], $options);
        } elseif (stripos($name, 'hall-') == 0) {
            $config = $this->config['default'];
            $config['database'] = HallDomainService::getHallID();
            return $this->connector()->connect($config, $options);
        } 

        if (isset($this->config['clusters'][$name])) {
            return $this->resolveCluster($name);
        }

        throw new InvalidArgumentException("Redis connection [{$name}] not configured.");
    }

    /**
     * Resolve the given cluster connection by name.
     *
     * @param  string  $name
     * @return \Illuminate\Redis\Connections\Connection
     */
    protected function resolveCluster($name)
    {
        $clusterOptions = $this->config['clusters']['options'] ?? [];

        return $this->connector()->connectToCluster(
            $this->config['clusters'][$name], $clusterOptions, $this->config['options'] ?? []
        );
    }
}
